package com.smartthinking.CICPNL.home.activity;

import java.util.ArrayList;
import java.util.Dictionary;

import org.xml.sax.helpers.ParserAdapter;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources.Theme;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.smartthinking.CICPNL.Chat;
import com.smartthinking.CICPNL.DatabaseHelper;
import com.smartthinking.CICPNL.EncuestasPager;
import com.smartthinking.CICPNL.InfoGeneral;
import com.smartthinking.CICPNL.R;
import com.smartthinking.CICPNL.UpdateDB;

@SuppressLint("NewApi")
public class MainActivity extends Activity {

	private static Bitmap imageOriginal, imageScaled;
	private static Matrix matrix;
	public static ArrayList<Dictionary> ValidaUpdater = null;
	public static ArrayList<Dictionary> TraerDatos = null;
	public static ArrayList<Dictionary<String,String>> Splash = null;
	private View texto;
	private String strTexto;
	private double grados;
	private float relacion = (float)0;
	private int wWidth;
	private int imgWidth;
	private int wHeight;
	private int tTop;
	public Utilities cnnIntenet;
	private ImageView dialer;
	private int dialerHeight, dialerWidth;
	private GestureDetector detector;

	public final static String SONIDO = "com.smartthinking.pediatria.SONIDO";
	public static ArrayList<Dictionary<String,String>> Banners = null;
	
	// needed for detecting the inversed rotations
	private boolean[] quadrantTouched;
			private boolean allowRotating;
			public Dialog dialog;
			public TextView textview;
			public Dialog progress;

			@Override
			public void onCreate(Bundle savedInstanceState) {
				super.onCreate(savedInstanceState);
				requestWindowFeature(Window.FEATURE_NO_TITLE);
				setContentView(R.layout.activity_main);
				cnnIntenet = new Utilities();
				
				new AsyncUpdate().execute();
				
				//splash
				try{
					String qry = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = 1 and b.ban_nombre = 'SPLASH DESCARGA' ORDER BY b.ban_nombre";
					Splash = Utilities.qry2(getApplicationContext(), qry);
					
			    	if(Splash.size()>0){
			    		Dictionary<String, String> dic = Splash.get(0);
				    	String strPoster = dic.get("ban_url").toString();
					    String strTimer = dic.get("ban_timer").toString();
					    String strPatrocinador = dic.get("pat_idr").toString();
					    if (strPoster.equals("null")) {
					        strPoster = "";
					    }
					    if(strPoster.length()>0){
							Intent intent = new Intent(this, Splash2.class);
							Bundle bund = new Bundle();
							bund.putString("PUT_IMG",strPoster);
							bund.putString("PUT_PAT",strPatrocinador);
							bund.putString("PUT_TIME",strTimer);
							intent.putExtras(bund);
							startActivity(intent);
					    }
				    }
				}catch(Exception ex){}

				Display mDisplay= getWindowManager().getDefaultDisplay();
				wWidth = mDisplay.getWidth();
				wHeight = mDisplay.getHeight();

				// load the image only once
				dialer = (ImageView) findViewById(R.id.imageView_ring);
				if (imageOriginal == null) {
					if(wWidth == 240){
						dialer.setImageResource(R.drawable.menu_rueda_240);
						imgWidth = 240;
						imageOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.menu_rueda_240);
					}else if (wWidth == 320){
						dialer.setImageResource(R.drawable.menu_rueda_320);
						imgWidth = 320;
						imageOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.menu_rueda_320);
					}else if (wWidth == 480){
						dialer.setImageResource(R.drawable.menu_rueda_480);
						imgWidth = 480;
						imageOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.menu_rueda_480);
					}else{
						imgWidth = 620;
						imageOriginal = BitmapFactory.decodeResource(getResources(), R.drawable.menu_rueda);    
					}
				}
				imgWidth = 640;
				relacion = (float)wWidth /(float)imgWidth;

				// initialize the matrix only once
				if (matrix == null) {
					matrix = new Matrix();
				} else {
					// not needed, you can also post the matrix immediately to restore the old state
					matrix.reset();
				}

				detector = new GestureDetector(this, new MyGestureDetector());

				// there is no 0th quadrant, to keep it simple the first value gets ignored
				quadrantTouched = new boolean[] { false, false, false, false, false };

				allowRotating = true;
				dialer.setOnTouchListener(new MyOnTouchListener());
				dialer.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

					@Override
					public void onGlobalLayout() {
						// method called more than once, but the values only need to be initialized one time
						if (dialerHeight == 0 || dialerWidth == 0) {
							dialerHeight = dialer.getHeight();
							dialerWidth = dialer.getWidth();

							// resize
							Matrix resize = new Matrix();
							resize.postScale((float)Math.min(dialerWidth, dialerHeight) / (float)imageOriginal.getWidth(), (float)Math.min(dialerWidth, dialerHeight) / (float)imageOriginal.getHeight());
							imageScaled = Bitmap.createBitmap(imageOriginal, 0, 0, imageOriginal.getWidth(), imageOriginal.getHeight(), resize, false);

							// translate to the image view's center
							float translateX = dialerWidth / 2 - imageScaled.getWidth() / 2;
							float translateY = dialerHeight / 2 - imageScaled.getHeight() / 2;
							matrix.postTranslate(translateX, translateY);

							dialer.setImageBitmap(imageScaled);
							dialer.setImageMatrix(matrix);


							//ajustar boton central
							Button btn = (Button)findViewById(R.id.menu_btn_menu);
							String temp = (736*0.49*relacion) + "";
							temp = temp.substring(0,temp.indexOf("."));
							int w = Integer.parseInt(temp);

							RelativeLayout.LayoutParams rel_btn = new RelativeLayout.LayoutParams(w, w);
							//rel_btn.topMargin = t;
							rel_btn.addRule(RelativeLayout.CENTER_HORIZONTAL);
							rel_btn.addRule(RelativeLayout.CENTER_VERTICAL);
							btn.setLayoutParams(rel_btn);

							//ajustar altura del texto---Se ajusto posici�n Altura 0.21 por 0.26 RIGM
							//temp = (736*0.26*relacion) + "";
							temp = (wHeight*.15) + "";
							temp = temp.substring(0,temp.indexOf("."));
							tTop = Integer.parseInt(temp);

							//dibujar texto curvo
							strTexto = MainActivity.this.getString(R.string.modulo_informacion);
							texto = new GraphicsView(getApplicationContext(),strTexto);
							if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
								texto.setLayerType(View.LAYER_TYPE_SOFTWARE, null);     
							}
							RelativeLayout lay = (RelativeLayout)findViewById(R.id.menu_lay);
							lay.addView(texto);
							grados = 10;
						}
					}
				});
			}

			public class AsyncUpdate extends AsyncTask<Void, Integer, Void>{
				int isFirstDownload = 0;
				int isNetwork = 0;
				int isOk = 0;
				SharedPreferences preferences;

				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					progress = ProgressDialog.show(MainActivity.this, "",MainActivity.this.getString(R.string.msg_cargando));
				}

				@Override
				protected Void doInBackground(Void... params) {
					preferences = MainActivity.this.getSharedPreferences("prefs", MODE_PRIVATE);
					
					//primero subo encuestas comentarios y cupones 
					if(Utilities.isNetwork()){
						if(!preferences.getString("dbversion", "0").equals("0")){
							UploadComentarios();
							UploadEncuestas();
							UploadCupones();
						}
					}
					
					//Luego valido la version
					if(preferences.getString("dbversion", "0").equals("0")){
						//primera descarga
						isFirstDownload = 1;
						if(Utilities.isNetwork()){
							isNetwork = 1; 
							String strqry = "select version,fecha from ctrl_updates";
							cnnIntenet.qry(MainActivity.this,cnnIntenet.escape(strqry));
							ValidaUpdater = cnnIntenet.Actividades;
						}else{
							isNetwork = 0;
						}
					}else{
						//actualizacion
						isFirstDownload = 0;
						if(Utilities.isNetwork()){
							isNetwork = 1; 
							String strqry = "select version,fecha from ctrl_updates";
							cnnIntenet.qry(MainActivity.this,cnnIntenet.escape(strqry));
							ValidaUpdater = cnnIntenet.Actividades;
						}else{
							isNetwork = 0;
						}
					}
					
				    String qry  = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = 1 and b.ban_nombre = 'BANNER HOME' ORDER BY b.ban_nombre";
					Banners = Utilities.qry2(getApplicationContext(), qry);
					
					return null;
				}

				@Override
				protected void onPostExecute(Void result) {
					super.onPostExecute(result);
					progress.dismiss();

					if((isFirstDownload == 1)&&(isNetwork == 0)){
						Log.i("1", "(isFirstDownload == 1)&&(isNetwork == 0)");
						AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);  
						ad.setTitle(MainActivity.this.getString(R.string.msg_sin_internet));  
						ad.setMessage(MainActivity.this.getString(R.string.msg_descarga_reintentar));   
						ad.setPositiveButton(MainActivity.this.getString(R.string.msg_si), new DialogInterface.OnClickListener() {  
							public void onClick(DialogInterface dialog, int id) {  
								dialog.dismiss();
								new AsyncUpdate().execute();
							}  
						}).setNegativeButton(MainActivity.this.getString(R.string.msg_no), new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								finish();
							}
						});  
						ad.show();
					}else if((isFirstDownload == 1)&&(isNetwork == 1)){
						Log.i("2", "(isFirstDownload == 1)&&(isNetwork == 1)");
						if(ValidaUpdater.size() > 0){
							AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);  
							ad.setTitle(MainActivity.this.getString(R.string.msg_descarga_titulo));  
							ad.setMessage(MainActivity.this.getString(R.string.msg_descarga));
							ad.setPositiveButton(MainActivity.this.getString(R.string.msg_si), new DialogInterface.OnClickListener() {  
								public void onClick(DialogInterface dialog, int id) {  
									dialog.dismiss();
									Intent goUpdate = new Intent(MainActivity.this, UpdateDB.class);
									goUpdate.putExtra("dbversion", ""+ValidaUpdater.get(0).get("version").toString());
									startActivity(goUpdate);
								}  
							}).setNegativeButton(MainActivity.this.getString(R.string.msg_no), new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									dialog.dismiss();
								}
							});  
							ad.show();
						}else{
							AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);  
							ad.setTitle("Error");  
							ad.setMessage("Error del servidor");
							ad.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {  
								public void onClick(DialogInterface dialog, int id) {  
									finish();
								}  
							});  
							ad.show();
							
						}
						

					}else if((isFirstDownload == 0)&&(isNetwork == 0)){
						Log.i("3", "(isFirstDownload == 0)&&(isNetwork == 0)");
					}else if((isFirstDownload == 0)&&(isNetwork == 1)){
						Log.i("4", "(isFirstDownload == 0)&&(isNetwork == 1)");
						if(ValidaUpdater.size() > 0){
							if((!preferences.getString("dbversion", "0").equals(""+ValidaUpdater.get(0).get("version").toString()))){
								Log.i("4", "ACTUALIZACION");
								AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);  
								ad.setTitle(MainActivity.this.getString(R.string.msg_descarga_titulo));  
								ad.setMessage(MainActivity.this.getString(R.string.msg_descarga_act));   
								ad.setPositiveButton(MainActivity.this.getString(R.string.msg_si), new DialogInterface.OnClickListener() {  
									public void onClick(DialogInterface dialog, int id) {  
										dialog.dismiss();
										Intent goUpdate = new Intent(MainActivity.this, UpdateDB.class);
										goUpdate.putExtra("dbversion", ""+ValidaUpdater.get(0).get("version").toString());
										startActivity(goUpdate);
									}  
								}).setNegativeButton(MainActivity.this.getString(R.string.msg_no), new DialogInterface.OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {
										dialog.dismiss();
									}
								});  
								ad.show();
							}else{
								Log.i("4", "NADA");
							}
						}else{
							AlertDialog.Builder ad = new AlertDialog.Builder(MainActivity.this);  
							ad.setTitle("Error");  
							ad.setMessage("Error del servidor");
							ad.setPositiveButton("Aceptar", new DialogInterface.OnClickListener() {  
								public void onClick(DialogInterface dialog, int id) {  
									finish();
								}  
							});  
							ad.show();
						}
						
						//presenta banner
						if(Banners.size()>0){
							ImageView banner = (ImageView) findViewById(R.id.menu_img_banner);

				        	BitmapFactory.Options bmpOptions = new BitmapFactory.Options();
				        	bmpOptions.inSampleSize = 1;
				        	Bitmap bmp = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + "/Pediatria/" + Banners.get(0).get("ban_url").toString(),bmpOptions);
				        	banner.setImageBitmap(bmp);
				        	banner.setOnClickListener(new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									// TODO Auto-generated method stub
									Intent intent = new Intent(MainActivity.this, PatrocinadoresDetalle.class);
									Bundle bund = new Bundle();
									bund.putString("idpatrocinador", Banners.get(0).get("pat_idr").toString());
									intent.putExtras(bund);
									startActivity(intent);
								}
							});
						}
						
					}//if first download
				}//post-execute
			}

			/**
			 * Rotate the dialer.
			 * 
			 * @param degrees The degrees, the dialer should get rotated.
			 */
			private void rotateDialer(float degrees) {
				matrix.postRotate(degrees, dialerWidth / 2, dialerHeight / 2);
				dialer.setImageMatrix(matrix);
				/*
                Mostramos titulo
                son 18 secciones 360/18 = 20¼ cada una
				 */
				grados = grados + degrees;
				if(grados < 0){
					grados = grados + 360;
				}else if (grados>360){
					grados = grados -360;
				}
				String txt = "";
				if(grados >= 0 && grados < 20 ){
					txt = this.getString(R.string.modulo_informacion);
				}else if (grados >= 20 && grados < 40 ){
					txt = this.getString(R.string.modulo_mensajes);
				}else if (grados >= 40 && grados < 60 ){
					txt = this.getString(R.string.modulo_lanzamientos);
				}else if (grados >= 60 && grados < 80 ){
					txt = this.getString(R.string.modulo_patrocinios);
				}else if (grados >= 80 && grados < 100 ){
					txt = this.getString(R.string.modulo_noticias);
				}else if (grados >= 100 && grados < 120 ){
					txt = this.getString(R.string.modulo_favoritos);
				}else if (grados >= 120 && grados < 140 ){
					txt = this.getString(R.string.modulo_ps);
				}else if (grados >= 140 && grados < 160 ){
					txt = this.getString(R.string.modulo_destino);
				}else if (grados >= 160 && grados < 180 ){
					txt = this.getString(R.string.modulo_qr);
				}else if (grados >= 180 && grados < 200 ){
					txt = this.getString(R.string.modulo_registro);
				}else if (grados >= 200 && grados < 220 ){
					txt = this.getString(R.string.modulo_encuestas);
				}else if (grados >= 220 && grados < 240 ){
					txt = this.getString(R.string.modulo_cupones);
				}else if (grados >= 240 && grados < 260 ){
					txt = this.getString(R.string.modulo_buscar);
				}else if (grados >= 260 && grados < 280 ){
					txt = this.getString(R.string.modulo_chat);
				}else if (grados >= 280 && grados < 300 ){
					txt = this.getString(R.string.modulo_ponentes);
				}else if (grados >= 300 && grados < 320 ){
					txt = this.getString(R.string.modulo_programa);
				}else if (grados >= 320 && grados < 340 ){
					txt = this.getString(R.string.modulo_expositores);
				}else if (grados >= 340 && grados < 360 ){
					txt = this.getString(R.string.modulo_plano);
				}

				if(txt != strTexto){
					RelativeLayout lay = (RelativeLayout)findViewById(R.id.menu_lay);
					lay.removeView(texto);

					strTexto = txt;
					texto = new GraphicsView(this,strTexto);
					if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
						texto.setLayerType(View.LAYER_TYPE_SOFTWARE, null);     
					}
					lay.addView(texto);
					
					if(sonido){
						dialer.playSoundEffect(SoundEffectConstants.CLICK);	
					}
					//dialer.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY, HapticFeedbackConstants.FLAG_IGNORE_GLOBAL_SETTING);
				}
			}

			/**
			 * @return The angle of the unit circle with the image view's center
			 */
			private double getAngle(double xTouch, double yTouch) {
				double x = xTouch - (dialerWidth / 2d);
				double y = dialerHeight - yTouch - (dialerHeight / 2d);

				switch (getQuadrant(x, y)) {
				case 1:
					return Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;

				case 2:
				case 3:
					return 180 - (Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI);

				case 4:
					return 360 + Math.asin(y / Math.hypot(x, y)) * 180 / Math.PI;

				default:
					// ignore, does not happen
					return 0;
				}
			}

			/**
			 * @return The selected quadrant.
			 */
			private static int getQuadrant(double x, double y) {
				if (x >= 0) {
					return y >= 0 ? 1 : 4;
				} else {
					return y >= 0 ? 2 : 3;
				}
			}

			/**
			 * Simple implementation of an {@link OnTouchListener} for registering the dialer's touch events. 
			 */
			private class MyOnTouchListener implements OnTouchListener {
				private double startAngle;

				@Override
				public boolean onTouch(View v, MotionEvent event) {
					switch (event.getAction()) {
					case MotionEvent.ACTION_DOWN:
						// reset the touched quadrants
						for (int i = 0; i < quadrantTouched.length; i++) {
							quadrantTouched[i] = false;
						}

						allowRotating = false;
						startAngle = getAngle(event.getX(), event.getY());
						break;
					case MotionEvent.ACTION_MOVE:
						double currentAngle = getAngle(event.getX(), event.getY());
						rotateDialer((float) (startAngle - currentAngle));
						startAngle = currentAngle;
						break;
					case MotionEvent.ACTION_UP:
						allowRotating = true;
						break;
					}

					// set the touched quadrant to true
					quadrantTouched[getQuadrant(event.getX() - (dialerWidth / 2), dialerHeight - event.getY() - (dialerHeight / 2))] = true;
					detector.onTouchEvent(event);
					return true;
				}
			}

			/**
			 * Simple implementation of a {@link SimpleOnGestureListener} for detecting a fling event. 
			 */
			private class MyGestureDetector extends SimpleOnGestureListener {
				@Override
				public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
					// get the quadrant of the start and the end of the fling
					int q1 = getQuadrant(e1.getX() - (dialerWidth / 2), dialerHeight - e1.getY() - (dialerHeight / 2));
					int q2 = getQuadrant(e2.getX() - (dialerWidth / 2), dialerHeight - e2.getY() - (dialerHeight / 2));

					// the inversed rotations
					if ((q1 == 2 && q2 == 2 && Math.abs(velocityX) < Math.abs(velocityY))
							|| (q1 == 3 && q2 == 3)
							|| (q1 == 1 && q2 == 3)
							|| (q1 == 4 && q2 == 4 && Math.abs(velocityX) > Math.abs(velocityY))
							|| ((q1 == 2 && q2 == 3) || (q1 == 3 && q2 == 2))
							|| ((q1 == 3 && q2 == 4) || (q1 == 4 && q2 == 3))
							|| (q1 == 2 && q2 == 4 && quadrantTouched[3])
							|| (q1 == 4 && q2 == 2 && quadrantTouched[3])) {

						dialer.post(new FlingRunnable(-1 * (velocityX + velocityY)));
					} else {
						// the normal rotation
						dialer.post(new FlingRunnable(velocityX + velocityY));
					}
					return true;
				}
			}

			/**
			 * A {@link Runnable} for animating the the dialer's fling.
			 */
			private class FlingRunnable implements Runnable {
				private float velocity;

				public FlingRunnable(float velocity) {
					this.velocity = velocity;
				}

				@Override
				public void run() {
					if (Math.abs(velocity) > 5 && allowRotating) {
						rotateDialer(velocity / 75);
						velocity /= 1.0666F;

						// post this instance again
						dialer.post(this);
					}
				}
			}

			public class GraphicsView extends View {
				private String MY_TEXT = "Informacin";
				private Path mArc;
				private Paint mPaintText;

				public GraphicsView(Context context, String texto) {
					super(context);     
					MY_TEXT = texto;

					String temp = (wHeight * 0.9)+"";
					
					temp = temp.substring(0,temp.indexOf("."));
					int mHeight = Integer.parseInt(temp);

					mArc = new Path();
					
					RectF oval = new RectF(-30,tTop,(wWidth+30),mHeight);
					mArc.addArc(oval, -180, 180);

					mPaintText = new Paint(Paint.ANTI_ALIAS_FLAG);
					mPaintText.setStyle(Paint.Style.FILL_AND_STROKE);
					mPaintText.setTypeface(Typeface.DEFAULT_BOLD);
					mPaintText.setColor(0xff770044);

					mPaintText.setTextSize(25f);
					/*
              if(wWidth>550){
                  mPaintText.setTextSize(30f);
              }else if(wWidth<400){
                  mPaintText.setTextSize(20f);
              }else{
                  mPaintText.setTextSize(25f);  
              }*/

					mPaintText.setTextAlign(Paint.Align.CENTER);
				}

				@Override
				protected void onDraw(Canvas canvas) {
					canvas.drawTextOnPath(MY_TEXT, mArc, 0, 20, mPaintText);
					invalidate();
				}
			}

			public void goExpo(View view){
				Intent goInfogeneral = new Intent(MainActivity.this, InfoGeneral.class);
				startActivity(goInfogeneral);
			}

			boolean sonido = true;
			public void goInfo(View view){
				Intent intent = new Intent(this, InfoSmart.class);
				intent.putExtra(SONIDO, sonido);
				startActivityForResult(intent,101);
			}
			
		    @Override
		    public void onActivityResult(int requestCode, int resultCode, Intent data) {
		        super.onActivityResult(requestCode, resultCode, data);
		        switch(requestCode) { 
		        case (101) : {
		        	if (resultCode == Activity.RESULT_OK) {
		        		sonido = data.getBooleanExtra(SONIDO,true);
		        	}
		          break;
		          }
		      }
		    }

			public void goMenu(View view){
				Intent intent = null;

				if(strTexto.equals(this.getString(R.string.modulo_informacion))){
					intent = new Intent(this, InformationEvento.class);
					intent.putExtra("PUT_OCULTAR", true);
				}else if(strTexto.equals(this.getString(R.string.modulo_mensajes))){
					//NUEVO
					intent = new Intent(this, Mensajes.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_lanzamientos))){
					//NUEVO
					intent = new Intent(this, Lanzamientos.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_patrocinios))){
					intent = new Intent(this, Patrocinadores.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_noticias))){
					intent = new Intent(this, Noticias.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_favoritos))){
					//NUEVO
					intent = new Intent(this, Favoritos.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_ps))){
					//NUEVO
					intent = new Intent(this, ProgramaSocial.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_destino))){
					//NUEVO
					intent = new Intent(this, Destino.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_qr))){
					intent = new Intent(this,EventosLectorQR.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_registro))){
					intent = new Intent(this, EventosRegistro.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_encuestas))){
					intent = new Intent(this, EncuestasPager.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_cupones))){
					intent = new Intent(this, Cupon.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_buscar))){
					//NUEVO
					intent = new Intent(this, Buscador.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_chat))){
					//NUEVO-------------
					intent = new Intent(this, Chat.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_ponentes))){
					intent = new Intent(this, Ponentes.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_programa))){
					intent = new Intent(this, Programa.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_expositores))){
					intent = new Intent(this, Expositores.class);
				}else if(strTexto.equals(this.getString(R.string.modulo_plano))){
					intent = new Intent(this, Plano.class);
				}

				if(intent != null){
					startActivity(intent);
				}else{
					Toast.makeText(getApplicationContext(),"Modulo " + strTexto,Toast.LENGTH_SHORT).show(); 
				}
			}

			public void LocalDB(){
				cnnIntenet.alert(this, "No cuenta con servicio de Internet, trabajando localmente...");
				if (cnnIntenet.checkDB(this)==true) {
					cnnIntenet.alert(this, "DBASE existente, trabajando localmente...");
				}else{
					cnnIntenet.alert(this, "Descargando DBASE...");
				}
			}

			public void UploadComentarios(){
				ArrayList<Dictionary<String,String>> Comments = null;
			    String qry  = "select * from calificacion where enviado = 'false'";
				Comments = Utilities.qry2(getApplicationContext(), qry);
			    
			    if (Comments.size()>0) {
			    	String strSQL = "";
			        try{
			            for (int i=0; i< Comments.size(); i++) {
			                strSQL = strSQL + "insert into calificacion (cal_idr,cal_tipo,obj_idr,cal_calif,cal_coments) select (select coalesce(max(cal_idr + 1),1) from calificacion),'"+Comments.get(i).get("tipo")+"',"+Comments.get(i).get("idr")+","+Comments.get(i).get("calif")+",'"+Comments.get(i).get("comentario")+"'; ";
			            }
			            strSQL = getString(R.string.QRY_URL_COMMAND) + cnnIntenet.escape(strSQL);
				        cnnIntenet.sendAndStore(strSQL);
			            
			    		DatabaseHelper usdbh = new DatabaseHelper(this);
			    		SQLiteDatabase db = usdbh.getWritableDatabase();
			    		db.execSQL("update calificacion set enviado = 'true'");
			    		db.close();
			    		usdbh.close();
			        }catch (Exception ex) {
			            return;
			        }
			    }
			}
			
			public void UploadEncuestas(){
				ArrayList<Dictionary<String,String>> Encuestas = null;
			    String qry  = "select * from encuestas_respuestas where enc_enviado = 'false'";
			    Encuestas = Utilities.qry2(getApplicationContext(), qry);
				
			    if (Encuestas.size()>0) {
			    	String strSQL = "";
			        try{
			            for (int i=0; i< Encuestas.size(); i++) {
			                strSQL = strSQL + "delete from encuestas_respuestas where enc_idr = '"+Encuestas.get(i).get("enc_idr")+"' and udid = '"+Encuestas.get(i).get("udid")+"'; insert into encuestas_respuestas (enc_idr, opc_idr, udid) select "+Encuestas.get(i).get("enc_idr")+","+Encuestas.get(i).get("opc_idr")+", '"+Encuestas.get(i).get("udid")+"';";
			            }
			            strSQL = getString(R.string.QRY_URL_COMMAND) + cnnIntenet.escape(strSQL);
				        cnnIntenet.sendAndStore(strSQL);
			            
			    		DatabaseHelper usdbh = new DatabaseHelper(this);
			    		SQLiteDatabase db = usdbh.getWritableDatabase();
			    		db.execSQL("update encuestas_respuestas set enc_enviado = 'true'");
			    		db.close();
			    		usdbh.close();
			        }catch (Exception ex) {
			            return;
			        }
			    }
			}
			
			public void UploadCupones(){
				ArrayList<Dictionary<String,String>> Cupones = null;
			    String qry  = "select * from cupones_emitidos where cup_enviado = 'false'";
			    Cupones = Utilities.qry2(getApplicationContext(), qry);
				
			    if (Cupones.size()>0) {
			    	String strSQL = "";			        try{
			            for (int i=0; i< Cupones.size(); i++) {
			                strSQL = strSQL + "delete from cupones where cup_idr = "+Cupones.get(i).get("cup_idr")+" and eve_idr = "+Cupones.get(i).get("eve_idr")+" and udid = '"+Cupones.get(i).get("udid")+"'; insert into cupones_emitidos (cup_idr, eve_idr, udid, cup_fecha) select "+Cupones.get(i).get("cup_idr")+", "+Cupones.get(i).get("eve_idr")+", '"+Cupones.get(i).get("udid")+"', '"+Cupones.get(i).get("cup_fecha")+"'; ";
			            }
			            strSQL = getString(R.string.QRY_URL_COMMAND) + cnnIntenet.escape(strSQL);
				        cnnIntenet.sendAndStore(strSQL);
			            
			    		DatabaseHelper usdbh = new DatabaseHelper(this);
			    		SQLiteDatabase db = usdbh.getWritableDatabase();
			    		db.execSQL("update cupones_emitidos set cup_enviado = 'true'");
			    		db.close();
			    		usdbh.close();
			        }catch (Exception ex) {
			            return;
			        }
			    }
			}
}